package com.sharkburner.aeris.service.user.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sharkburner.aeris.bean.UserBean;
import com.sharkburner.aeris.dao.GroupDao;
import com.sharkburner.aeris.dao.UserDao;
import com.sharkburner.aeris.dao.entity.Group;
import com.sharkburner.aeris.dao.entity.User;
import com.sharkburner.aeris.service.user.UserService;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao userDao;
	@Autowired
	private GroupDao groupDao;

	public User findUser(long id) {
		return userDao.get(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.sharkburner.aeris.service.user.UserService#save(com.sharkburner.aeris
	 * .bean.UserBean)
	 */
	@Transactional
	public void save(UserBean userBean) {
		User user = new User();
		user.setFullName(userBean.getFullName());
		user.setEmail(userBean.getEmail());
		user.setPassword(userBean.getPassword());
		user.setGroup(getUserGroup(userBean.getGroupId()));
		userDao.saveOrUpdate(user);
	}

	/**
	 * @param id
	 * @return
	 */
	private Group getUserGroup(int id) {
		if (id == 0)
			id = 1;
		Group group = groupDao.get(id);
		if (group == null) {
			group = new Group();
			// TODO: Insert group if not exist
		}

		return group;
	}

	@Override
	@Transactional
	public UserBean findByName(String name) {
		UserBean userBean = userDao.findByName(name);
		return userBean;
	}

	@Override
	@Transactional
	public UserBean find(String name, String password) {
		return userDao.find(name, password);
	}
}
